package com.hxfeng.authdemo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxfeng.authdemo.entity.MyUser;
import com.hxfeng.authdemo.entity.User;
import com.hxfeng.authdemo.mapper.UserMapper;
import com.hxfeng.authdemo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author hxfeng
 * @since 2022-05-18
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService, UserDetailsService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    PasswordEncoder bCryptPasswordEncoder;

    @Override
    public void addUser(User user) {
        String plainPassword = user.getPassword();
        String encodePassword = bCryptPasswordEncoder.encode(plainPassword);
        user.setPassword(encodePassword);
        save(user);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = getById(Long.parseLong(username));
        MyUser myUser = new MyUser();
        myUser.setUsername(user.getUserId().toString());
        myUser.setPassword(user.getPassword());
        return myUser;
    }
}
